package javaNIO1.Selectors;

import java.sql.SQLOutput;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with Intel IDEA.
 *
 * @Auther: gjt
 * @Date: 2024/8/3 11:16
 */
public class BackSlashes {
    public static void main(String[] args) {
        method2();
    }

    private static void method1(){
        // 在输入中把 "a\b" 替换成 xyz 或者abc
        String rep ="a\\\\b";
        String input = "> XYZ <=> ABC <";

        try {
            Pattern compile = Pattern.compile("ABC|XYZ");
            Matcher matcher = compile.matcher(input);
            System.out.println(matcher.replaceFirst(rep));
            System.out.println(matcher.replaceAll(rep));

            rep = "\\\\r\\\\n";
            input = "line 1\nline 2\nline 3\n";
            Pattern compile1 = Pattern.compile("\\n");
            Matcher matcher1 = compile1.matcher(input);
            System.out.println("");
            System.out.println("Before:");
            System.out.println(input);

            System.out.println("After (dos-ified, escaped):");
            System.out.println(matcher1.replaceAll(rep));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static void method2(){
        String input  = "Thanks, thanks very much";
        String regex = "([Tt]hanks)";
        try {
            Pattern compile = Pattern.compile(regex);
            Matcher matcher = compile.matcher(input);
            // 继承了CharSequence 接口
            StringBuffer stringBuffer = new StringBuffer();

            while(matcher.find()){
                if(matcher.group(1).equals("T")){
                    matcher.appendReplacement(stringBuffer,"Thank you");
                }else {
                    matcher.appendReplacement(stringBuffer,"thank you");
                }
            }

            matcher.appendTail(stringBuffer);
            System.out.println(stringBuffer + "1");

            // 再替换中使用$n
            stringBuffer.setLength(0);

            /**
             * 无参: 将使用上次为Matcher 设置的CharSequence
             * 如果希望对新的字符序列（CharSequence）进行匹配 可以将新的CharSequence 传递给Matcher 的reset()方法
             * 类似重新匹配
             */
            matcher.reset();

            String replacement ="$1hank you";
            while(matcher.find()){

                // 把匹配的字符序列加上匹配的字符序列的第一位去除    放到 stringBuffer 中
                matcher.appendReplacement(stringBuffer,replacement);
            }

            matcher.appendTail(stringBuffer);
            System.out.println(stringBuffer + "2");

            System.out.println(matcher.replaceAll(replacement) + "3");
            System.out.println(input.replaceAll(regex,replacement) + "4");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void method3(){
        String input  = "Thanks, thanks ve.ry mu.ch";
        String regex = "\\p{L}";

        Pattern compile = Pattern.compile(regex);
    }
}
